<template>
  <div class="app-container">

    <!-- 查询和其他操作 -->
    <div class="filter-container">
      <el-form :inline="true">
        <el-form-item label=" 机构  "  prop="departmentId">
          <el-select v-model="listQuery.departmentId" clearable placeholder="请选择">
            <el-option
              v-for="item in departmentList"
              :key="item.id"
              :label="item.name"
              :value="item.id"/>
          </el-select>
        </el-form-item>
       <!-- <el-form-item label="停车场">
          <el-select v-model="listQuery.parkId" clearable placeholder="请选择">
            <el-option
              v-for="item in allParkList"
              :key="item.id"
              :label="item.name"
              :value="item.id"/>
          </el-select>
        </el-form-item> -->

        <!-- <el-form-item label="状态">
          <el-select v-model="listQuery.status" placeholder="请选择" style="width: 90px;">
            <el-option
              v-for="item in status_options"
              :key="item.value"
              :label="item.label"
              :value="item.value"/>
          </el-select>
        </el-form-item> -->

        <el-button class="filter-item" type="primary" icon="el-icon-search" @click="handleFilter">查找</el-button>

        <el-button
          v-hasPermi="['admin:parkMp:create']"
          class="filter-item"
          style="float:right"
          type="primary"
          icon="el-icon-plus"
          @click="startAdd">添加</el-button>
      </el-form>
    </div>

    <!-- 查询结果 -->
    <el-table v-loading="listLoading" :data="list" element-loading-text="正在查询中。。。" border fit highlight-current-row >

      <el-table-column align="center" label="公众号名称" prop="name"/>

      <el-table-column align="center" label="所属机构" prop="departmentNameStr" show-overflow-tooltip/>

      <!-- <el-table-column align="center" label="停车场" prop="parkName"/> -->

      <el-table-column align="center" label="微信appId" prop="appId"/>

      <el-table-column align="center" label="微信secret" prop="secret"/>

      <el-table-column align="center" label="添加时间" prop="createTime"/>

      <!-- <el-table-column align="center" label="状态" prop="status">
        <template slot-scope="scope">
          <el-tag >{{ getStatus(scope.row.status) }}</el-tag>
        </template>
      </el-table-column> -->

      <el-table-column align="center" label="操作" width="250" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            v-hasPermi="['admin:parkMp:update']"
            type="primary"
            size="small"
            @click="startEditMp(scope.row)">编辑</el-button>
          <el-button
            v-hasPermi="['admin:parkMp:updateTemplateMsgConf']"
            type="primary"
            size="small"
            @click="messegeConfig(scope.row)">模板消息配置</el-button>
         <!-- <el-button
            v-hasPermi="['admin:parkMp:delete']"
            type="primary"
            size="small"
            @click="deleteMp(scope.row.name, scope.row.id)">删除</el-button> -->
        </template>
      </el-table-column>
    </el-table>

    <pagination v-show="total>0" :total="total" :page.sync="listQuery.page" :limit.sync="listQuery.pageSize" @pagination="getList" />

    <el-dialog :close-on-click-modal="false" :title="dialogTitle" :visible.sync="dialogFormVisible" width="28%">
      <el-form ref="dialogForm"  :rules="formRules" :model="dialogForm" 
      :label-width="dialogTitle == '模板消息配置详情' ? '170px' : '120px'">
        <div v-if="dialogTitle == '模板消息配置详情'">
          <el-form-item :label="item.label + '  模板消息id'" :prop="item.value" v-for="(item,index) in messegeList" :key="index">
            <el-input v-model="dialogForm[item.value]" clearable class="filter-item" style="width: 100%;" placeholder=""/>
          </el-form-item>
        </div>
        <div v-else>
          <el-form-item label=" 机构  " prop="deptIds">
            <el-select v-model="dialogForm.deptIds" style="width: 100%;" multiple  placeholder="请选择"
            @change="selectDepartmentId">
              <el-option
                v-for="item in departmentList"
                :key="item.id"
                :label="item.name"
                :value="item.id"/>
            </el-select>
          </el-form-item>

          <el-form-item label=" 公众号名称  " prop="name">
            <el-input v-model="dialogForm.name" clearable class="filter-item" style="width: 100%;" placeholder=""/>
          </el-form-item>
          <el-form-item label=" 微信appId  " prop="appId">
            <el-input v-model="dialogForm.appId" clearable class="filter-item" style="width: 100%;" placeholder=""/>
          </el-form-item>
          <el-form-item label=" 微信secret  " prop="secret">
            <el-input v-model="dialogForm.secret" clearable class="filter-item" style="width: 100%;" placeholder=""/>
          </el-form-item>
          <el-form-item label="token" prop="token">
            <el-input v-model="dialogForm.token" clearable class="filter-item" style="width: 100%;" placeholder=""/>
          </el-form-item>
          <el-form-item label="aesKey" prop="aesKey">
            <el-input v-model="dialogForm.aesKey" clearable class="filter-item" style="width: 100%;" placeholder=""/>
          </el-form-item>
        </div>
      </el-form>

      <div slot="footer" class="dialog-footer" align="center">
        <el-button @click="confirmEdit('dialogForm')">确定</el-button>
        <el-button @click="dialogFormVisible = false">取消</el-button>
      </div>
    </el-dialog>

  </div>
</template>

<script>
/* eslint-disable eqeqeq */

import { fetchList, deleteParkMp, createParkMp, updateParkMp,parkMpDetail,listTemplateMsgConf
,updateTemplateMsgConf } from '@/api/parkMp'
import { selectList } from '@/api/passway'
import { getDepartmentList } from '@/api/base'
import Pagination from '@/components/Pagination' // Secondary package based on el-pagination
import { getData, } from '@/api/system/dictionary'
export default {
  name: 'mp',
  components: { Pagination },
  dicts:[],
  data() {
    return {
      list: null,
      total: 0,
      listLoading: true,
      status_options: [{
        value: '',
        label: '全部'
      }, {
        value: '1',
        label: '启用'
      }, {
        value: '2',
        label: '停用'
      }],
      listQuery: {
        page: 1,
        pageSize: 20
      },
      downloadLoading: false,
      dialogFormVisible: false,
      dialogForm: {},
      dialogType: 1,
      dialogTitle:'',
      departmentList: [],
      parkList: [],
      allParkList: [],
      passwayList: [],
      qrcodeDialogVisible: false,
      formRules1: {
        name: [{ required: true, message: '请输入公众号名称', trigger: 'blur' }],
        appId: [{ required: true, message: '请输入微信appId', trigger: 'blur' }],
        secret: [{ required: true, message: '请输入微信secret', trigger: 'blur' }],
        departmentId: [{ required: true, message: '请选择机构名称', validator: this.checkSelected, trigger: 'change' }],
        parkId: [{ required: true, message: '请选择停车场', validator: this.checkSelected, trigger: 'change' }]
      },
      formRules:{},
      messegeList:[],//消息模板字典数据
      messegeForm:[],//消息模板数据
    }
  },
  created() {
    getDepartmentList({pushed: false,paid: true}).then(res => {
      this.departmentList = res.data || []
      this.getList()
    })
  },
  methods: {
    async messegeConfig(row){//消息配置点击
      this.dialogForm = {}
      this.formRules = {}
      this.dialogTitle = '模板消息配置详情'
      this.dialogFormVisible = true
      this.$nextTick(() => {
        this.$refs.dialogForm.clearValidate()
      })
      listTemplateMsgConf(row.id).then(async response => {
        let messegeForm = response.data || []
        let list = await this.getData()
        this.messegeList = [...list]
        let form = {}
        let formRules = {}
        list.map(item=>{
          let obj = messegeForm.find(item1=>item1.type == item.value)
          form[item.value] = obj ? obj.templateMsgId : ''
          formRules[item.value] = [{ required: true, message: `请输入${item.label}模板消息id`, trigger: 'blur' }]
        })
        this.dialogForm = {...form,parkMpId:row.id}
        // this.formRules = {...formRules}
      });
    },
    async getData(){//消息模板
			let res = await getData('EParkMpTemplateMsgType')
			let list = res.data || []
      return list
		},
    // 校验下拉框
    checkSelected(rule, value, callback) {
      if (!value) {
        callback(new Error(rule.message))
      } else {
        callback()
      }
    },
    getList() {
      this.listLoading = true
      fetchList(this.listQuery).then(response => {
        let data = response.data || {}
				let list = data.list || []
        this.list = list.map(item=>{
					let deptList = item.deptList || []
          let departmentNameList = item.departmentNameList || []
					return {
						...item,
            departmentNameStr:departmentNameList.toString(),
					}
				})
        this.total = data.total || 0
        this.listLoading = false
      })
    },
    handleFilter() {
      this.listQuery.page = 1
      this.getList()
    },
    getType(type) {
      if (type == 1) {
        return '入口'
      }
      return '出口'
    },
    // getStatus(status) {
    //   if (status == 1) {
    //     return '启用'
    //   }
    //   return '停用'
    // },
    deleteMp(name, parkId) {
      this.$confirm(`您确定删除公众号：${name}`, '温馨提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        deleteParkMp({ id: parkId }).then(response => {
          this.$message({
            message: '删除成功!',
            type: 'success'
          })
          this.getList()
        })
      })
    },
    startAdd() {
      this.dialogForm = {}
      this.dialogFormVisible = true
      this.dialogTitle = '添加微信公众号'
      this.formRules = {...this.formRules1}
      this.$nextTick(() => {
        this.$refs.dialogForm.clearValidate()
      })
    },
    confirmEdit(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          if(this.dialogTitle == '模板消息配置详情') {
            let dialogForm = {...this.dialogForm}
            let form = {parkMpId:dialogForm.parkMpId }
            let templateMsgConfList = this.messegeList.map(item=>{
              return {
                type: item.value,
                templateMsgId: dialogForm[item.value],
              }
            })
            form.templateMsgConfList = [...templateMsgConfList]
            updateTemplateMsgConf(form).then(response => {
              this.$message({message: '配置成功!',type: 'success'})
              this.getList()
              this.dialogFormVisible = false
              this.dialogForm = {}
            })
          }else{
            this.dialogForm.channel = 1
            if (!this.dialogForm.id) {
              createParkMp(this.dialogForm).then(response => {
                this.$message({
                  message: '添加成功!',
                  type: 'success'
                })
                this.getList()
                this.dialogFormVisible = false
                this.dialogForm = {}
              })
            } else {
              updateParkMp(this.dialogForm).then(response => {
                this.$message({
                  message: '修改成功!',
                  type: 'success'
                })
                this.getList()
                this.dialogFormVisible = false
                this.dialogForm = {}
              })
            }
          }
					
        }
      })
    },
    reset() {
      this.dialogForm = {};
      this.formRules = {...this.formRules1}
      this.resetForm("dialogForm");
    },
    startEditMp(row) {
      this.reset();
      parkMpDetail(row.id).then(response => {
        this.dialogFormVisible = true
        this.dialogTitle = '修改微信公众号'
          let data = response.data || {}
        this.dialogForm = {
          ...data,
        }
        this.parkList = []
        this.$nextTick(() => {
          this.$refs.dialogForm.clearValidate()
        })
      });
    },
    selectDepartmentId(event) {
      this.parkList = []
    },
    selectParkId(event) {
      this.passwayList = []
      var getMps = { 'parkId': event, 'page': 1 }
      selectList(getMps).then(response => {
        let data = response.data || {}
        this.passwayList = data.list || []
      })
    }

  }
}
</script>
